package cn.com.gas.controller;

import com.alibaba.excel.EasyExcelFactory;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.metadata.Sheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.com.common.constants.Constants;
import cn.com.common.result.DataResult;
import cn.com.gas.entity.GasPaytaxEntity;
import cn.com.gas.service.GasPaytaxService;
import cn.com.gas.vo.excel.GasPaytaxExcel;
import cn.com.system.service.impl.HttpSessionService;
import cn.com.util.TsBqUtils;



/**
 * 纳税记录
 *
 * @author shaochangyang
 * @email l2l84o7o5@live.com
 * @date 2024-04-12 16:28:51
 */
@RestController
@RequestMapping("/gas/paytax")
public class GasPaytaxController {
    @Autowired
    private GasPaytaxService gasPaytaxService;
    @Autowired
    private HttpSessionService httpSessionService;
    @Value("${file.path}")
	private String filePath;
	@Value("${file.url}")
	private String fileUrl;
	
    @ApiOperation(value = "新增")
    @PostMapping("/add")
    // @RequiresPermissions("gasPaytax:add")
    @ResponseBody
    public DataResult add(@RequestBody GasPaytaxEntity gasPaytax){
        
    	gasPaytax.setDeleted(Constants.DELETEED_NOT);
    	gasPaytax.setCreateId(httpSessionService.getCurrentUserId());
    	gasPaytax.setCreateTime(new Date());
    	
    	gasPaytaxService.save(gasPaytax);
        return DataResult.success();
    }

    @ApiOperation(value = "删除")
    @DeleteMapping("/delete")
    // @RequiresPermissions("gasPaytax:delete")
    @ResponseBody
    public DataResult delete(@RequestBody @ApiParam(value = "id集合") List<String> ids){
        
    	gasPaytaxService.removeByIds(ids);
        return DataResult.success();
    }

    @ApiOperation(value = "更新")
    @PutMapping("/update")
    // @RequiresPermissions("gasPaytax:update")
    @ResponseBody
    public DataResult update(@RequestBody GasPaytaxEntity gasPaytax){
        
    	gasPaytax.setUpdateId(httpSessionService.getCurrentUserId());
    	gasPaytax.setUpdateTime(new Date());
		
    	gasPaytaxService.updateById(gasPaytax);
        return DataResult.success();
    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
	@ApiOperation(value = "查询分页数据")
    @PostMapping("/list")
    // @RequiresPermissions("gasPaytax:list")
    @ResponseBody
    public DataResult findListByPage(@RequestBody GasPaytaxEntity gasPaytax) throws ParseException{
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	Page page = new Page(gasPaytax.getPage(), gasPaytax.getLimit());
        LambdaQueryWrapper<GasPaytaxEntity> queryWrapper = Wrappers.lambdaQuery();
        //查询条件示例
        if (!StringUtils.isEmpty(gasPaytax.getCreateTimeStart())) {
			queryWrapper.ge(GasPaytaxEntity::getCreateTime, sdf.parse(gasPaytax.getCreateTimeStart() + " 00:00:00"));
		}
		if (!StringUtils.isEmpty(gasPaytax.getCreateTimeEnd())) {
			queryWrapper.le(GasPaytaxEntity::getCreateTime, sdf.parse(gasPaytax.getCreateTimeEnd() + " 23:59:59"));
		}

		if (!StringUtils.isEmpty(gasPaytax.getTaxorgName())) {
			queryWrapper.eq(GasPaytaxEntity::getTaxorgName, gasPaytax.getTaxorgName());
		}
		
		if (!StringUtils.isEmpty(gasPaytax.getStationName())) {
			queryWrapper.eq(GasPaytaxEntity::getStationName, gasPaytax.getStationName());
		}
		
        IPage<GasPaytaxEntity> iPage = gasPaytaxService.page(page, queryWrapper);
        return DataResult.success(iPage);
    }
    
    
	@PostMapping("/exportData")
	@ResponseBody
	public DataResult exportData(@RequestBody GasPaytaxEntity gasPaytax)
			throws java.io.IOException, ParseException {

    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        LambdaQueryWrapper<GasPaytaxEntity> queryWrapper = Wrappers.lambdaQuery();
        //查询条件示例
        if (!StringUtils.isEmpty(gasPaytax.getCreateTimeStart())) {
			queryWrapper.ge(GasPaytaxEntity::getCreateTime, sdf.parse(gasPaytax.getCreateTimeStart() + " 00:00:00"));
		}
		if (!StringUtils.isEmpty(gasPaytax.getCreateTimeEnd())) {
			queryWrapper.le(GasPaytaxEntity::getCreateTime, sdf.parse(gasPaytax.getCreateTimeEnd() + " 23:59:59"));
		}

		if (!StringUtils.isEmpty(gasPaytax.getTaxorgName())) {
			queryWrapper.eq(GasPaytaxEntity::getTaxorgName, gasPaytax.getTaxorgName());
		}
		
		if (!StringUtils.isEmpty(gasPaytax.getStationName())) {
			queryWrapper.eq(GasPaytaxEntity::getStationName, gasPaytax.getStationName());
		}

		List<GasPaytaxEntity> list = gasPaytaxService.list(queryWrapper);

		if (list.size() > 0) {

			List<GasPaytaxExcel> gasPaytaxExcelList = new ArrayList<>();

			for (GasPaytaxEntity entity : list) {

				GasPaytaxExcel gasPaytaxExcel = GasPaytaxExcel.builder()
						.id(entity.getId())
						.stationName(entity.getStationName())
						.taxorgName(entity.getTaxorgName())
						.paytaxTime(entity.getPaytaxTime())
						.paytaxMoney(entity.getPaytaxMoney())
						.createId(entity.getCreateId())
						.createTime(entity.getCreateTime())
						.build();

				gasPaytaxExcelList.add(gasPaytaxExcel);

			}

			String fileName = TsBqUtils.getUUID() + ".xlsx";

			String excelPath = filePath + fileName;
			OutputStream out = null;

			try {
				out = new FileOutputStream(excelPath);
				ExcelWriter writer = EasyExcelFactory.getWriter(out);

				Sheet sheet1 = new Sheet(1, 0, GasPaytaxExcel.class);
				sheet1.setSheetName("数据");
				writer.write(gasPaytaxExcelList, sheet1);
				// 将上下文中的最终 outputStream 写入到指定文件中
				writer.finish();
				File excelFile = new File(excelPath);
				List<Object> excelFileInfo = new ArrayList<>();
				excelFileInfo.add(fileName);
				excelFileInfo.add(excelFile.length());
				excelFileInfo.add(fileUrl + "/" + fileName);

				return DataResult.success(excelFileInfo);

			} catch (FileNotFoundException e) {
				e.printStackTrace();
				return DataResult.fail("xlsx生成失败：" + e.toString());
			} finally {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
					return DataResult.fail("xlsx生成失败：" + e.toString());
				}

			}

		} else {
			return DataResult.fail("传入的ids为null！");
		}
	}
    

}
